<?php
/**
 * @todo 把配置写成类的形式,就可以通过 autoloader组件自己加载了.
 * @author bluelevin(at)gmail.com
 *
 */
class LyConfig {
	protected $configDir;
	protected $cacheDir;
	static $config = array();
	function setConfigDir($dir){
		$dir = trim($dir,'/\\ ');
		if(!is_dir($dir)){
			return false;
		}
		$this->configDir = $dir;
	}
	function setCacheDir($dir){
		$dir = trim($dir,'/\\ ');
		if(!is_dir($dir)){
			@mkdir($dir,0777,true);
		}
		$this->cacheDir = $dir;
	}
	function parseConfig($dev = false,$loadAllAtFirst = true){
		
		if(is_file($tmpFile = $this->buildFilename('__all__config__')) && false === $dev){
			if($loadAllAtFirst){
				self::$config = include $tmpFile;
			}
		}else{
			$dir = $this->configDir;
			if($handle = opendir($dir)){
				while(false !== ($file = readdir($handle))){
					$filePath = $dir.DIRECTORY_SEPARATOR.$file;
					if(is_file($filePath) && pathinfo($file,PATHINFO_EXTENSION) == 'ini'){
						$arrayIni = array_change_key_case(parse_ini_file($filePath,true));
						self::$config = array_merge(self::$config,$arrayIni);
					}
				}
			} 
			$allFilename = $this->buildFilename('__all__config__');
			$allContent = "<?php \n return ".var_export(self::$config,true)."\n?>";
			file_put_contents($allFilename,$allContent);
			foreach (self::$config as $key => $value){
				$newContent = "<?php \n return ".var_export($value,true)."\n?>";
				$newFilename = $this->buildFilename($key);
				file_put_contents($newFilename,$newContent);
			}
			/**
			 $content = "<?php return \n".var_export($this->config,true)."\n?>";
			 file_put_contents($filename,$content);
			 */
		}
	}
	function getConfig($keyName,$default = null){
		$keyName = trim($keyName,' ._/\\');
		if(!strpos($keyName,'_')){
			$key = strtolower($keyName);
			if(isset(self::$config[$key])){
				return self::$config[$key];
			}else{
				$filename = $this->buildFilename($key);
				if(is_file($filename)){
					self::$config[$key] = include $filename;
					return self::$config[$key];
				}else{
					return $default;
				}
			}
		}else{
			$array = explode('_',$keyName,2);
			$mod = strtolower($array[0]);
			$keyName = $array[1];
			if(isset(self::$config[$mod][$keyName])){
				return self::$config[$mod][$keyName];
			}else{
				$filename = $this->buildFilename($mod);
				if(is_file($filename)){
					self::$config[$mod] = include $filename;
					if(isset(self::$config[$mod][$keyName])){
						return self::$config[$mod][$keyName];
					}
				}
				return $default;				
			}
		}
	}
	function __get($keyName){
		return $this->getConfig($keyName);
	}
	function buildFilename($key){
		$path = $this->cacheDir.DIRECTORY_SEPARATOR.'__config__cache__';
		if(!is_dir($path)){
			@mkdir($path,0777,true);
		}
		return $path.DIRECTORY_SEPARATOR.$key.'.config.php';
	}
}